package com.shengde.jinwawaforleader.network.photos;

import android.app.Activity;
import android.app.ProgressDialog;
import android.text.TextUtils;

import com.shengde.jinwawaforleader.HomeApplication;

import java.util.ArrayList;
import java.util.List;

public class ProImageUploadThread extends Thread {
	private Activity act;
	private List<String> fileList;
	private UploadCompleteCallback callback;

	public static interface UploadCompleteCallback {
		public void onComplete(List<String> serverFileList);
	}

	public ProImageUploadThread(List<String> fileList, Activity act,
								UploadCompleteCallback callback) {
		this.fileList = fileList;
		this.act = act;
		this.callback = callback;
	}

	public void runInMainThread(Runnable r) {
		// if (Looper.myLooper() != Looper.getMainLooper())
		HomeApplication.mHander.post(r);
	}

	//内部变量
	private ProgressDialog progressDialog;
	private int total = 0;
	private int cur = 0;
	List<String> serverFileList = new ArrayList<String>();

	@Override
	public void run() {
		if (fileList == null || fileList.size() < 1)
			return;
		try {

			total = fileList.size();
			String serverFile = null;
			runInMainThread(new Runnable() {
				public void run() {
					if (progressDialog == null)
						progressDialog = ProgressDialog.show(act, null,
								"正在上传...", true, false);

				}
			});
			for (int i = 0; i < total; i++) {
				cur = i + 1;
				runInMainThread(new Runnable() {
					public void run() {
						String str = "正在上传..." + cur + "/" + total;
						progressDialog.setMessage(str);

					}
				});
				try {
					serverFile = ProImageUpload.upload(fileList.get(i));
				} catch (Exception e) {
					e.printStackTrace();
				} catch (OutOfMemoryError e) {
					e.printStackTrace();
				}
				if (!TextUtils.isEmpty(serverFile))
					serverFileList.add(serverFile);
			}
		} catch (Exception e) {
			runInMainThread(new Runnable() {
				public void run() {
					HomeApplication.showToastShort("上传失败");
				}
			});
		} finally {
			runInMainThread(new Runnable() {
				public void run() {
					if (progressDialog != null && progressDialog.isShowing())
						progressDialog.dismiss();
					progressDialog = null;
					if (callback != null)
						callback.onComplete(serverFileList);
					HomeApplication.showToastShort("上传成功");
				}
			});
		}
		super.run();
	}
}
